#include "pal/laneLibuv.h"
#include "CxlUtil.h"
#include "voiceChedaoji.h"

static uv_loop_t *loop;
static uv_timer_t laneIntervalReq;
static uv_timer_t mainWorkSetTimeOut;
static uv_timer_t reRegisterSetTimeOut;
static uv_stream_t *serverStream;
static uv_tcp_t lane_socket;
static uv_connect_t client;

void laneLoopInit()
{
    loop = getLoop();
    uv_timer_init(loop, &laneIntervalReq);
    uv_timer_init(loop, &mainWorkSetTimeOut);
    uv_timer_init(loop, &reRegisterSetTimeOut);
}

void laneInterval(void *cb, void *param, uint16_t time)
{
    laneIntervalReq.data = param;
    uv_timer_start(&laneIntervalReq, cb, 0, time);
}

void laneClearInterval()
{
    uv_timer_stop(&laneIntervalReq);
}

void laneRestart()
{
    uv_timer_again(&laneIntervalReq);
}

void laneConnect(const char *ip, int port, uv_connect_cb cb)
{
    uv_tcp_init(loop, &lane_socket);

    struct sockaddr_in dest;
    uv_ip4_addr(ip, port, &dest);

    uv_tcp_connect(&client, &lane_socket, (const struct sockaddr *)&dest, cb);
    audioNetConnecting();
}

uv_connect_t *getLaneClientConnect()
{
    return &client;
}

void laneMainWorkSetTimeout(void *cb, uint16_t time)
{
    if (uv_timer_get_due_in(&mainWorkSetTimeOut) > 0)
    {
        return;
    }
    else
    {
        uv_timer_start(&mainWorkSetTimeOut, cb, time, 0);
    }
}

void laneReRegisterSetTimeout(void *cb, uint16_t time)
{
    if (uv_timer_get_due_in(&reRegisterSetTimeOut) > 0)
    {
        return;
    }
    else
    {
        uv_timer_start(&reRegisterSetTimeOut, cb, time, 0);
    }
}